/**
 * 49. 字母异位词分组
 * https://leetcode-cn.com/problems/group-anagrams/
 */
const { displayNestedArray } = require('../../libs/public');

/**
 * @param {string} str
 * @return {string}
 */
function hash(str) {
  if (!str) return str;
  const map = new Map();
  const { length } = str;
  for (let i = 0; i < length; i += 1) {
    const char = str.charAt(i);
    map.set(char, (map.get(char) || 0) + 1);
  }
  return Array
    .from(map.keys())
    .sort()
    .map((key) => `${key}${map.get(key)}`)
    .join('');
}

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
function groupAnagrams(strs) {
  const map = new Map();
  strs.forEach((str) => {
    const key = hash(str);
    if (map.has(key)) {
      map.get(key).push(str);
    } else {
      map.set(key, [str]);
    }
  });
  return Array.from(map.values());
}

console.log(displayNestedArray(groupAnagrams(['eat', 'tea', 'tan', 'ate', 'nat', 'bat'])));
console.log(displayNestedArray(groupAnagrams([''])));
console.log(displayNestedArray(groupAnagrams(['a'])));
console.log(displayNestedArray(groupAnagrams(['ddddddddddg', 'dgggggggggg'])));
